﻿using Client;
using Shared.Method;
using Shared.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DataStatisticsSystem
{
    public partial class FormStatistics : Form
    {
        private List<NODE> _listNode = null;//排序NODE
        private List<LINE> _listLine = null;//产线信息

        private System.Timers.Timer autoFlushTimer = null;//自动刷新产能数据
        private int lineIndex = 0;//选择的产线的Index

        public FormStatistics()
        {
            InitializeComponent();
        }

        //show product statistics
        private void ButtonFlush_Click(object sender, EventArgs e)
        {
            try
            {
                this.listViewStatistics.Items.Clear();
                //获取需要查询的数据信息
                DateTime startDate = dateTimePickerChoiceDate.Value.Date;
                //MessageBox.Show(startDate.ToString());

                int startHour = int.Parse(this.comboBoxHour.Text);
                int totalHour = int.Parse(this.textBoxTotalHour.Text);
                long lineId = long.Parse(this.comboBoxLineId.Text);

                this.labelLineIdShow.Text = "产线-"+this.comboBoxLineId.Text;

                //判断输入的时间是否可行
                if (startDate.AddHours(startHour) > DateTime.Now.AddHours(-1))
                {
                    MessageBox.Show("开始时间有误，需要比当前时间小一小时以上");
                    return;
                }

                //判断需要统计的时间是否大于1小时
                if (totalHour < 1 || totalHour > 24)
                {
                    MessageBox.Show("统计时间需要大于1小时，小于24小时");
                    return;
                }

                //获取需要统计的真实小时数
                if (startDate.AddHours(startHour + totalHour) > DateTime.Now.AddHours(-1))
                {
                    totalHour = (DateTime.Now.AddHours(-1) - startDate.AddHours(startHour)).Hours;//其中1表示需要统计的最开始的小时
                }

                int[] onepass = new int[20];
                int[] pass = new int[20];
                int[] total = new int[20];

                PRODUCT_COUNT_DATA countW = new PRODUCT_COUNT_DATA();//查询产能的数据

                //查询产能
                for (int i = 0; i <= totalHour; i++)
                {
                    countW.SetWhere();
                    countW.COUNT_DATE = startDate.AddHours(startHour + i).Date;
                    countW.COUNT_TIME = startDate.AddHours(startHour + i).Hour;
                    countW.LINE_ID = lineId;

                    var selectCountData = MethodWcf.SelectProductCountDataClient(countW);

                    //MessageBox.Show(countW.COUNT_DATE.ToString()+countW.COUNT_TIME+selectCountData.result + selectCountData.message);

                    if (selectCountData.result)
                    {
                        //获取排序后产能
                        var countDataSort = (from n in _listNode
                                             from c in selectCountData.value
                                             where c.NODE_ID == n.ID
                                             select new { n.ID, c.ONETIME_PASS, c.PASS, c.TOTAL }).ToList();

                        //MessageBox.Show(countDataSort.Count.ToString());

                        //将数据写入listView当中，并记录所有的数据
                        ListViewItem item = new ListViewItem();
                        item.Text = countW.COUNT_TIME.ToString();//显示时间
                        for (int j = 0, k = 0; j < _listNode.Count && k < countDataSort.Count;)
                        {
                            if (_listNode[j].ID == countDataSort[k].ID)
                            {
                                pass[j] += countDataSort[k].PASS;
                                onepass[j] += countDataSort[k].ONETIME_PASS;
                                total[j] += countDataSort[k].TOTAL;

                                item.SubItems.Add(countDataSort[k].TOTAL.ToString());

                                j++;
                                k++;
                            }
                            else
                            {
                                item.SubItems.Add("");
                                j++;
                            }
                        }
                        //展示数据
                        this.listViewStatistics.Items.Add(item);
                    }
                }

                //展示onetimepass、pass、total
                ListViewItem[] items = new ListViewItem[3];

                items[0] = new ListViewItem();
                items[1] = new ListViewItem();
                items[2] = new ListViewItem();

                items[0].Text = "总数";
                items[1].Text = "直通率";
                items[2].Text = "通过率";

                for (int i = 0; i < _listNode.Count; i++)
                {
                    if (total[i] == 0)
                    {
                        items[0].SubItems.Add("");//总数为0，不显示
                        items[1].SubItems.Add("");//总数为0，不显示
                        items[2].SubItems.Add("");//总数为0，不显示
                    }
                    else
                    {
                        items[0].SubItems.Add(total[i].ToString());
                        items[1].SubItems.Add(((double)onepass[i] / total[i]).ToString("p"));
                        items[2].SubItems.Add(((double)pass[i] / total[i]).ToString("p"));
                    }
                }

                this.listViewStatistics.Items.AddRange(items);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void FormStatistics_Load(object sender, EventArgs e)
        {
            //判断软件版本是否与数据库匹配，若不匹配，不允许启动
            string version = Application.ProductVersion;
            string name = Application.ProductName;

            string sqlVersionCheck = $"SELECT CONVERT(VARCHAR,COUNT(*)) FROM SOFTWARE WHERE NAME='{name}' AND VERSION='{version}'";

            var retVersionCheck = MethodWcf.ExecuteReturnSQLClient(sqlVersionCheck);

            if (retVersionCheck != "1")
            {
                MessageBox.Show("软件版本不正确，请升级到最新版本");
                Close();
                return;
            }

            //实时产能
            LoadDefaultMsg();

            //修改默认日期为当前日期
            this.dateTimePickerChoiceDate.Value = DateTime.Today;
            //MessageBox.Show(DateTime.Today.ToString("yyyy-MM-dd"));

            //获取产线信息并导入combo中
            LINE lineW = new LINE();
            var selectLine = MethodWcf.SelectLineClient(lineW);
            if (selectLine.result)
            {
                _listLine = selectLine.value;
                for (int i = 0; i < selectLine.value.Count; i++)
                {
                    this.comboBoxLineId.Items.Add(selectLine.value[i].ID);
                }

                this.comboBoxLineId.SelectedIndex = 0;
            }


            //开启TIMER
            autoFlushTimer = new System.Timers.Timer();
            autoFlushTimer.Interval = 10000;//6秒间隔执行一次事件
            autoFlushTimer.Elapsed += AutoFlushTimer_Elapsed;//间隔发生事件

            if (checkBoxAutoFlush.Checked)
            {
                autoFlushTimer.Start();
            }

            //等比例缩放
            X = this.Width;
            Y = this.Height;

            SetTag(this);

        }

        private void AutoFlushTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //更新产线ID
            if (lineIndex >= this.comboBoxLineId.Items.Count)
            {
                lineIndex = 0;
            }

            //更新开始日期和时间
            if(DateTime.Now.Hour>=9 && DateTime.Now.Hour < 21)
            {
                ChangeForm(DateTime.Now.Date, 8, lineIndex);
            }
            else if(DateTime.Now.Hour<9)
            {
                //this.dateTimePickerChoiceDate.Value = DateTime.Now.AddDays(-1).Date;//前一天
                //this.comboBoxHour.SelectedIndex = 21;
                ChangeForm(DateTime.Now.AddDays(-1).Date, 20, lineIndex);
            }
            else
            {
                //this.dateTimePickerChoiceDate.Value = DateTime.Now.Date;
                //this.comboBoxHour.SelectedIndex = 21;
                ChangeForm(DateTime.Now.Date, 20, lineIndex);
            }


            //更新产线ID
            lineIndex++;
        }

        private void ChangeForm(DateTime date,int hourIndex,int lineIndex)
        { 
            if (this.InvokeRequired)
            {
                Action<DateTime, int, int> d = new Action<DateTime, int, int>(ChangeForm);
                Invoke(d, date, hourIndex, lineIndex);
            }
            else
            {
                this.comboBoxLineId.SelectedIndex = lineIndex;
                this.dateTimePickerChoiceDate.Value = date;
                this.comboBoxHour.SelectedIndex = hourIndex;

                //刷新
                this.buttonFlush.PerformClick();
            }
        }

        /// <summary>
        /// 自动刷新，每十秒刷新一次，换一下显示的产线，将没有数据的产线过滤掉
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBoxAutoFlush_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBoxAutoFlush.Checked)
            {
                autoFlushTimer.Start();
            }
            else
            {
                autoFlushTimer.Stop();
            }
        }

        private void FormStatistics_FormClosed(object sender, FormClosedEventArgs e)
        {
            autoFlushTimer?.Stop();
            autoFlushTimer?.Dispose();

            _targetTimer?.Stop();
        }


        #region 等比例缩放

        private float X = 0.0f;
        private float Y = 0.0f;

        private void SetTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Top + ":" + con.Left + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    SetTag(con);
                }
            }
        }
        private void SetControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                String[] mytags = con.Tag.ToString().Split(new char[] { ':' });
                float a = Convert.ToSingle(mytags[0]) * newx;
                con.Width = (int)a;
                a = Convert.ToSingle(mytags[1]) * newy;
                con.Height = (int)a;
                a = Convert.ToSingle(mytags[2]) * newy;
                con.Top = (int)a;
                a = Convert.ToSingle(mytags[3]) * newx;
                con.Left = (int)a;
                Single currectsize = Convert.ToSingle(mytags[4]) * newy;
                con.Font = new Font(con.Font.Name, currectsize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                {
                    SetControls(newx, newy, con);
                }
            }
        }

        private void FormStatistics_Resize(object sender, EventArgs e)
        {
            float newX = this.Width / X;
            float newY = this.Height / Y;

            SetControls(newX, newY, this);
            //this.Text = this.Width.ToString() + "*" + this.Height.ToString();
        }
        #endregion

        //private void buttonCountFlush_Click(object sender, EventArgs e)
        //{
        //    string[] x = new string[] { "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19" };
        //    double[] y = new double[] { 541, 574, 345, 854, 684, 257, 541, 574, 345, 854, 684, 257 };

        //    this.chartCount.Series[0].Points.DataBindXY(x, y);
        //    //this.chartCount.Series[0].Points[0].Color = Color.White;
        //    //this.chartCount.Series[0].Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Bright;
        //}


        #region 产能实时输出

        private long _lineId = 0;
        private long _lastNodeId = 0;
        private int _firstStartHour = 0;
        private int _secondStartHour = 0;
        private int _totalHour = 0;
        private int _firstTarget = 6000;
        private int _secondTarget = 4000;
        private int _defaultProduct = 600;

        private System.Timers.Timer _targetTimer = null;

        private List<PROVINCE> _listProvince = null;

        private void LoadDefaultMsg()
        {
            try
            {
                _lineId = long.Parse(AppSetting.GetValue("LineId"));
                _lastNodeId = long.Parse(AppSetting.GetValue("LastNodeId"));
                _firstStartHour = int.Parse(AppSetting.GetValue("FirstStartHour"));
                _secondStartHour = int.Parse(AppSetting.GetValue("SecondStartHour"));
                _totalHour = int.Parse(AppSetting.GetValue("TotalHour"));
                _firstTarget = int.Parse(AppSetting.GetValue("FirstTarget"));
                _secondTarget = int.Parse(AppSetting.GetValue("SecondTarget"));
                _defaultProduct = int.Parse(AppSetting.GetValue("DefaultProduct"));

                if (_firstStartHour >_secondStartHour)
                {
                    MessageBox.Show("白班夜班开始时间错误");
                    Close();
                }

                this.textBoxLine.Text = _lineId.ToString();

                _targetTimer = new System.Timers.Timer();
                _targetTimer.Interval = 1000;//1秒刷新一次
                _targetTimer.Elapsed += TargetTimer_Elapsed;

                _targetTimer?.Start();

                //初始化省份信息

                PROVINCE provW = new PROVINCE();
                var selectProv = MethodWcf.SelectProvinceClient(provW);
                if (selectProv.result)
                {
                    _listProvince = selectProv.value;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                Close();
            }
        }

        private void TargetTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //设置当前时间
            SetFormText(this.labelTimeNow, DateTime.Now.ToString("HH:mm:ss"));

            if (DateTime.Now.Second != 30) return;

            //修改内容
            DateTime startTime = new DateTime();
            DateTime endTime = DateTime.Now.AddMinutes(-3);

            int target = 0;
            double workerHours = 12;


            //判断时间，获得目标产能
            if (DateTime.Now.Hour >= _firstStartHour && DateTime.Now.Hour < _secondStartHour)
            {
                SetFormText(this.textBoxTodayTarget, _firstTarget.ToString()); target = _firstTarget;
                startTime = DateTime.Now.Date.AddHours(_firstStartHour);
            }
            else if (DateTime.Now.Hour >= _secondStartHour)
            {
                SetFormText(this.textBoxTodayTarget, _defaultProduct.ToString()); target = _secondTarget;
                startTime = DateTime.Now.Date.AddHours(_secondTarget);
            }
            else if (DateTime.Now.Hour < _firstStartHour)
            {
                SetFormText(this.textBoxTodayTarget, _secondTarget.ToString()); target = _secondTarget;
                startTime = DateTime.Now.AddDays(-1).Date.AddHours(_secondStartHour);
            }

            //获取标准产能
            SetFormText(this.textBoxOneHourCount, _defaultProduct.ToString());

            //工作时长
            workerHours = (endTime - startTime).TotalSeconds / 3600;

            //12点到18点减去一个小时
            if (DateTime.Now.Hour >= 12 && DateTime.Now.Hour < 18)
                workerHours -= 1;

            if (DateTime.Now.Hour >= 18 && DateTime.Now.Hour < 20)
                workerHours -= 0.5;

            string sql = string.Format("SELECT CONVERT(VARCHAR, COUNT(distinct MAC)) FROM View_Process WHERE NODE_ID={0} AND LINE_ID={1} AND TEST_RESULT='Y' AND END_TIME>='{2}' AND END_TIME<DATEADD(MINUTE,-3, GETDATE())", _lastNodeId, _lineId, startTime);
            string donePro = MethodWcf.ExecuteReturnSQLClient(sql);
            int done = 0;
            if (int.TryParse(donePro, out done) && done > 0)
            {
                //设置实时产量
                SetFormText(this.textBoxDone, donePro);

                //设置达成率
                SetFormText(this.textBoxOrder, ((double)done / target).ToString("p"));

                //计算平均产能
                SetFormText(this.textBoxAverage, ((double)done / workerHours).ToString("F2"));
            }
            //int done = (int)(double.Parse(selectAllPass.message) - 0.52 * double.Parse(selectDoubleTest.message));
            //MessageBox.Show(string.Format("总数：{0}，重复数量：{1}", selectAllPass.message, selectDoubleTest.message));


            //显示当前生产型号
            Device_Data deviceW = new Device_Data();
            deviceW.SetWhere(string.Format("MACAddr=(select top 1 MAC from TRCTL.dbo.PRODUCT where LINE_ID={0} and MAC is not null order by ID desc) ", _lineId, endTime));
            var selectDevice = MethodWcf.SelectDeviceDataClient(deviceW);

            if (selectDevice.result)
            {
                string province = (from p in _listProvince
                                   where p.PROVINCE_CODE == selectDevice.value[0].HW_PROVINCE_NAME
                                   select p.PROVINCE_NAME).FirstOrDefault();
                SetFormText(this.textBoxModemType, selectDevice.value[0].DeviceType + " " + province);

            }

#if false

            //在线不良数据
            int allProduct = 0;
            int notPassProduct = 0;

            //在线总数
            PRODUCT productW = new PRODUCT();
            productW.SetWhere(string.Format("LINE_ID={0} and END_TIME>='{1}' and END_TIME<'{2}'", _lineId, startTime, endTime));

            var selectProductAll = MethodWcf.SelectProductCountClient(productW);
            if (selectProductAll.result)
            {
                allProduct = int.Parse(selectProductAll.message);
                SetFormText(this.textBoxOnline, selectProductAll.message);
            }
            //不良数
            productW.SetWhere(string.Format("LINE_ID={0} and END_TIME>='{1}' and END_TIME<'{2}'and TEST_RESULT='N'", _lineId, startTime, endTime));
            var selectNotPass = MethodWcf.SelectProductCountClient(productW);
            if (selectNotPass.result)
            {
                notPassProduct = int.Parse(selectNotPass.message);
                SetFormText(this.textBoxBreak, selectNotPass.message);
            }
            //不良率
            SetFormText(this.textBoxBreakOrder, ((double)notPassProduct / allProduct).ToString("p"));
#endif

            //每小时的第6分钟第10秒显示产能数据
            if (DateTime.Now.Minute != 6 && DateTime.Now.Second != 10) return;

            //显示每小时产能数据
            PRODUCT_COUNT_DATA countW = new PRODUCT_COUNT_DATA();
            countW.SetWhere();

            countW.LINE_ID = _lineId;
            countW.NODE_ID = _lastNodeId;

            countW.SetWhere(string.Format("(COUNT_DATE ='{0}' or COUNT_DATE='{1}')", DateTime.Now.Date.AddDays(-1), DateTime.Now.Date));

            var selectCount = MethodWcf.SelectProductCountDataClient(countW);

            if (selectCount.result)
            {
                var counts = (from c in selectCount.value
                              where c.COUNT_DATE.AddHours(c.COUNT_TIME) >= startTime && c.COUNT_DATE.AddHours(c.COUNT_TIME) < endTime
                              orderby c.ID
                              select c).ToList();

                if (counts != null && counts.Count > 0)
                {
                    List<int> x = new List<int>();
                    List<int> y = new List<int>();

                    for (int i = 0; i < counts.Count; i++)
                    {
                        x.Add(counts[i].COUNT_TIME);
                        y.Add(counts[i].PASS);
                    }

                    SetChart(x, y);
                }
            }
        }

        private void SetChart(List<int>x,List<int> y)
        {
            if (this.chartCount.InvokeRequired)
            {
                Action< List < int >, List<int>> d = new Action<List<int>, List<int>>(SetChart);
                Invoke(d, x, y);
            }
            else
            {
                this.chartCount.Series[0].Points.DataBindXY(x,y);
            }
        }

        private void SetFormText(Control con, string text)
        {
            if (con.InvokeRequired)
            {
                Action<Control, string> d = new Action<Control, string>(SetFormText);
                Invoke(d, con, text);
            }
            else
            {
                con.Text = text;
            }
        }

#endregion

        private void CheckBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (this.checkBoxProductCount.Checked)
            {
                _targetTimer?.Start();
            }
            else
            {
                _targetTimer?.Stop();
            }
        }

        private void ComboBoxLineId_SelectedIndexChanged(object sender, EventArgs e)
        {
            //所有工序
            NODE nodeW = new NODE();
            nodeW.SetWhere(string.Format("FLOW_ID=(SELECT FLOW_ID FROM LINE WHERE ID={0})",comboBoxLineId.Text));
            var selectNode = MethodWcf.SelectNodeClient(nodeW);

            if (selectNode.result)
            {
                _listNode = (from n in selectNode.value
                             where n.FLAG == true
                             orderby n.FLOW_ID, n.SORT
                             select n).ToList();//排序后的工序

                for (int j = 1; j < this.listViewStatistics.Columns.Count; j++)
                {
                    this.listViewStatistics.Columns[j].Text = string.Empty;
                }

                this.listViewStatistics.Items.Clear();

                for (int i = 0; i < _listNode.Count; i++)
                {
                    this.listViewStatistics.Columns[i + 1].Text = _listNode[i].NAME;
                }
            }
            else
            {
                MessageBox.Show(selectNode.message);
                Close();
            }
        }

    }
}
